'use strict';

let fs = require('fs');
let path = require('path');
let router = require('koa-router')();


function searchControllers() {
    let files = fs.readdirSync(__dirname);
    let filterFilers = files.filter(fileName => {
        return fileName.endsWith('.js') && fileName !== 'index.js'
    })
    return filterFilers;
}

function register(files) {
    files.forEach(item => {
        let fullPath = path.join(__dirname, item);
        let routerObj = require(fullPath);

        for (let item in routerObj) {
            let valueArr = routerObj[item]
            // console.log(item);
            // console.log(valueArr);
            let type = valueArr[0];
            if (type === 'get') {
                if (valueArr.length === 2) {
                    let fn = valueArr[1];
                    router.get(item, fn)
                } else {
                    let auth = valueArr[1];
                    let fn = valueArr[2];
                    router.get(item, auth, fn)
                }
            } else if (type === 'post') {
                if (valueArr.length === 2) {
                    let fn = valueArr[1];
                    router.post(item, fn)
                } else {
                    let auth = valueArr[1];
                    let fn = valueArr[2];
                    router.post(item, auth, fn)
                }
            } else if (type === 'put') {
                if (valueArr.length === 2) {
                    let fn = valueArr[1];
                    router.put(item, fn)
                } else {
                    let auth = valueArr[1];
                    let fn = valueArr[2];
                    router.put(item, auth, fn)
                }
            } else if (type === 'delete') {
                if (valueArr.length === 2) {
                    let fn = valueArr[1];
                    router.delete(item, fn)
                } else {
                    let auth = valueArr[1];
                    let fn = valueArr[2];
                    router.delete(item, auth, fn)
                }
            }
        }
    })
}
module.exports = function () {
    let defaultControllerDir = __dirname;
    let files = searchControllers(defaultControllerDir)
    register(files);
    return router.routes()
}